package com.jin.webvideo.config.filter.access.rule;

import com.jin.webvideo.base.util.ObjectsUtil;
import com.jin.webvideo.config.filter.access.GlobalStore;
import com.jin.webvideo.config.filter.access.handler.AccessHandler;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.util.base.StringUtil;

import javax.servlet.http.HttpServletRequest;

public class PathAccessRule implements AccessHandler.AccessRule {
    private String[] pathPatterns;
    private String[] excludePatterns;

    public PathAccessRule(String[] pathPatterns, String[] excludePatterns) {
        this.pathPatterns = pathPatterns;
        this.excludePatterns = excludePatterns;
    }
    public PathAccessRule(String... pathPatterns) {
        this(pathPatterns, ObjectsUtil.Empty.STRINGS);
    }
    public PathAccessRule() {
        this(ObjectsUtil.Empty.STRINGS);
    }
    public void setExcludePatterns(String... excludePatterns) {
        this.excludePatterns = excludePatterns;
    }

    public void setPathPatterns(String... pathPatterns) {
        this.pathPatterns = pathPatterns;
    }

    public String[] getExcludePatterns() {
        return excludePatterns;
    }

    public String[] getPathPatterns() {
        return pathPatterns;
    }

    @Override
    public boolean compute(GlobalStore globalStore, SessionStore store, HttpServletRequest request) {
        return match(request.getRequestURI()) != null;
    }

    protected String match(String uri) {
        for (String path : pathPatterns) {
            if (StringUtil.match(path, uri) && !matchExcludePatterns(uri)) {
                return path;
            }
        }
        return null;
    }

    private boolean matchExcludePatterns(String uri) {
        for (String exclude : excludePatterns) {
            if (StringUtil.match(exclude, uri)) {
                return true;
            }
        }
        return false;
    }
}
